package cn.net.xyan.easy.webapp.base.controller;

import cn.net.xyan.easy.spring.core.exception.StatusAndMessageError;
import cn.net.xyan.easy.spring.core.utils.ExceptionUtils;
import cn.net.xyan.easy.spring.web.config.MVCApplicationContextConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiashenpin on 16/2/9.
 */
@org.springframework.web.bind.annotation.ControllerAdvice
public class ControllerAdvice {

    Logger logger = LoggerFactory.getLogger(ControllerAdvice.class);

    public static HttpServletRequest request(){
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
                .getRequest();
    }

    public static String contextPath(){
        try{
            HttpServletRequest curRequest = request();

            String contextPath = curRequest.getContextPath();

            if ("/".equals(contextPath))
                contextPath = "";

            return contextPath;

        }catch (Throwable e){
            return "";
        }
    }

    @ModelAttribute("webJarRoot")
    public String webJarRoot(){
        return MVCApplicationContextConfig.WEBJARROOT;
    }

    @ModelAttribute("contextPath")
    public String contextPathMA(){
        return contextPath();
    }

    @ModelAttribute("fullContextPath")
    public String fullContextPath(){
        try{
            HttpServletRequest request = request();
            return String.format("%s://%s:%d%s", request.getScheme(), request.getServerName(), request.getServerPort(), contextPath());
        }catch (Throwable e){
            return "";
        }
    }

    @ExceptionHandler({StatusAndMessageError.class,Throwable.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public @ResponseBody
    Map<String,Object> processStatusAndMessageError(NativeWebRequest request, Throwable e) {
        String traceMessage = ExceptionUtils.errorString(e);
        logger.error(traceMessage);
        Map<String,Object> result = new HashMap<>();
        result.put("msg",e.getMessage());
        result.put("stackTrace", ExceptionUtils.errorString(e));
        if (e instanceof StatusAndMessageError) {
            StatusAndMessageError error = (StatusAndMessageError) e;
            result.put("status", error.getStatus());
        }
        return result;
    }
}
